package com.yk.decode;

import com.yk.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by dingkl on 2017/8/9.
 */
public class RpcDecoder extends ByteToMessageDecoder{

    private Class<?> aClass;

    public RpcDecoder(Class<?> aClass){
        this.aClass = aClass;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //System.out.println("decode:"+aClass.getName());
        if (byteBuf.readableBytes()<4) //判断可读长度是否小于4
            return;
        byteBuf.markReaderIndex(); //标记ReaderIndex
        int dataLength = byteBuf.readInt();//读去传入的长度
        if (dataLength<0)//长度为0关闭不处理
            channelHandlerContext.close();
        if (byteBuf.readableBytes()<dataLength){//可读数据长度小于长度，标记给当前缓存readerIndex
            byteBuf.readerIndex();
            return;
        }
        byte[] data = new byte[dataLength];//设置字节数组
        byteBuf.readBytes(data);//把数据读入字节数组里面
        Object obj = SerializationUtil.deserialize(data,aClass);//转换
        list.add(obj);
    }
}
